package cz.myslivec.slovicka.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;

import cz.myslivec.slovicka.entity.Lesson;
import cz.myslivec.slovicka.entity.Vocable;

@Name("vocableDao")
@AutoCreate
public class VocableDao implements Serializable {
	private static final long serialVersionUID = -8127389614698469914L;

	@Logger
	Log log;

	@In
	private EntityManager entityManager;
	
	public Vocable get(Long id) {
		log.info("<><> vocableDao.get() {0}", id);
		if(id == null) {
			return null;
		}
		return entityManager.find(Vocable.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Vocable> list() {
		log.info("<><> vocableDao.list()");
		Query query = entityManager.createQuery("from Vocable");
		return query.getResultList();
	}
	
//	@SuppressWarnings("unchecked")
//	public List<Vocable> listByLesson(Lesson lesson) {
//		log.info("<><> vocableDao.listByLesson() {0}", lesson);
//		Query query = entityManager.createQuery("from Vocable voc where :lesson IN (voc.lessons)");
////		Query query = entityManager.createQuery("from Vocable voc where voc.id IN (select * from Leess_voc)");
//		
//		Query query = entityManager.createNativeQuery("SELECT * from VOCABLE voc where voc.ID_VOC IN (select ID_VOC from LESS_VOC lv where lv.ID_LES = :lesID)");
//		query.setParameter("lesID", lesson.getId());
//		return query.getResultList();
//	}
	
	public void delete(Vocable vocable) {
		Query query = entityManager.createQuery("DELETE FROM Vocable vo where vo=:vocable");
		query.setParameter("vocable", vocable);
		int sc = query.executeUpdate();
		if(sc == 1) {
			log.info("Successful deleting vocable: {0}", vocable.toString());
		} else {
			log.info("Unsuccessful deleting vocable: {0}", vocable.toString());
		} 
	}

}
